<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多人迷宫探险</title>
    <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Roboto:wght@400;700&display=swap"
          rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Roboto', sans-serif;
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
            color: #fff;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            overflow-x: hidden;
        }

        .container {
            width: 100%;
            max-width: 1200px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        header {
            text-align: center;
            padding: 20px 0;
            margin-bottom: 20px;
            width: 100%;
        }

        h1 {
            font-family: 'Press Start 2P', cursive;
            font-size: 2.5rem;
            color: #ffcc00;
            text-shadow: 3px 3px 0 #ff6b00, 5px 5px 0 rgba(0, 0, 0, 0.2);
            margin-bottom: 15px;
            letter-spacing: 2px;
        }

        .subtitle {
            font-size: 1.2rem;
            color: #ffdd99;
            max-width: 800px;
            margin: 0 auto 20px;
            line-height: 1.6;
        }

        .game-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 30px;
            width: 100%;
            margin-bottom: 30px;
        }

        .maze-section {
            flex: 1;
            min-width: 500px;
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .controls-section {
            width: 300px;
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .section-title {
            font-size: 1.5rem;
            color: #4dabf7;
            margin-bottom: 20px;
            text-align: center;
            font-weight: bold;
        }

        .maze-grid {
            display: grid;
            grid-template-columns: repeat(15, 1fr);
            gap: 2px;
            width: 100%;
            aspect-ratio: 1/1;
            background: #444;
            border: 3px solid #ff6b00;
            border-radius: 5px;
            overflow: hidden;
            position: relative;
        }

        .cell {
            background: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.3s;
            position: relative;
        }

        .cell.wall {
            background: #1a237e;
        }

        .cell.path {
            background: #222;
        }

        .cell.start {
            background: #4caf50;
        }

        .cell.end {
            background: #f44336;
        }

        .cell.player {
            position: relative;
            z-index: 10;
        }

        .player-marker {
            position: absolute;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 10px;
            z-index: 20;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
            transition: transform 0.2s;
        }

        .player-marker.active {
            transform: scale(1.2);
            box-shadow: 0 0 8px white;
            z-index: 30;
        }

        .player-1 {
            background: #ffeb3b;
            color: #000;
            top: 5px;
            left: 5px;
        }

        .player-2 {
            background: #2196F3;
            color: #fff;
            top: 5px;
            right: 5px;
        }

        .player-3 {
            background: #4CAF50;
            color: #fff;
            bottom: 5px;
            left: 5px;
        }

        .player-4 {
            background: #9C27B0;
            color: #fff;
            bottom: 5px;
            right: 5px;
        }

        .cell.visited {
            background: rgba(76, 175, 80, 0.3);
        }

        .btn {
            display: block;
            width: 100%;
            padding: 15px;
            margin: 15px 0;
            font-size: 1.1rem;
            font-weight: bold;
            color: white;
            background: linear-gradient(to right, #ff6b00, #ffcc00);
            border: none;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 5px 15px rgba(255, 107, 0, 0.4);
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(255, 107, 0, 0.6);
        }

        .btn:active {
            transform: translateY(1px);
        }

        .btn.secondary {
            background: linear-gradient(to right, #4a69bd, #6a89cc);
        }

        .btn:disabled {
            background: #666;
            cursor: not-allowed;
            opacity: 0.7;
        }

        .stats {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
            text-align: center;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            color: #ffcc00;
            margin: 10px 0;
        }

        .stat-label {
            font-size: 1rem;
            color: #aaa;
        }

        .instructions {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }

        .instructions h3 {
            color: #4dabf7;
            margin-bottom: 15px;
        }

        .instructions ul {
            padding-left: 20px;
        }

        .instructions li {
            margin-bottom: 10px;
            line-height: 1.5;
        }

        .key-controls {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-top: 20px;
        }

        .key {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid #ffcc00;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            font-weight: bold;
        }

        .difficulty-controls {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
        }

        .difficulty-btn {
            padding: 10px 15px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid #4dabf7;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
        }

        .difficulty-btn.active {
            background: #4dabf7;
            font-weight: bold;
        }

        .player-controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .player-btn {
            width: 22%;
            padding: 8px;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid #666;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .player-btn.active {
            border-color: #ffcc00;
            background: rgba(255, 204, 0, 0.2);
        }

        .player-btn.completed {
            border-color: #4CAF50;
            background: rgba(76, 175, 80, 0.3);
        }

        .player-btn .player-indicator {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin-bottom: 5px;
        }

        .player-btn-1 .player-indicator {
            background: #ffeb3b;
        }

        .player-btn-2 .player-indicator {
            background: #2196F3;
        }

        .player-btn-3 .player-indicator {
            background: #4CAF50;
        }

        .player-btn-4 .player-indicator {
            background: #9C27B0;
        }

        @media (max-width: 900px) {
            .game-container {
                flex-direction: column;
                align-items: center;
            }

            .maze-section {
                min-width: 100%;
            }

            .controls-section {
                width: 100%;
            }

            h1 {
                font-size: 1.8rem;
            }
        }

        /* 添加游戏信息显示样式 */
        .game-info {
            background: rgba(0, 0, 0, 0.7);
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
            text-align: center;
            width: 100%;
            max-width: 800px;
        }

        .game-info-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
        }

        .game-info-item {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 8px;
            padding: 10px;
        }

        .game-info-label {
            font-weight: bold;
            color: #4dabf7;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }

        .game-info-value {
            color: #ffcc00;
            font-size: 1.2rem;
            font-weight: bold;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .loading-spinner {
            border: 8px solid #f3f3f3;
            border-top: 8px solid #ff6b00;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading-text {
            font-size: 1.5rem;
            color: #fff;
        }

        .error-message {
            background: rgba(244, 67, 54, 0.8);
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            text-align: center;
            display: none;
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>多人迷宫探险</h1>
        <p class="subtitle">控制四个玩家从起点到达终点！使用方向键移动当前玩家，数字键1-4切换玩家。当前玩家：<span
                id="current-player-display">1</span></p>
    </header>

    <div class="game-info">
        <div class="game-info-grid">
            <div class="game-info-item">
                <div class="game-info-label">游戏ID</div>
                <div class="game-info-value" id="game-id-display">加载中...</div>
            </div>
            <div class="game-info-item">
                <div class="game-info-label">难度</div>
                <div class="game-info-value" id="difficulty-display">加载中...</div>
            </div>
            <div class="game-info-item">
                <div class="game-info-label">完成度</div>
                <div class="game-info-value" id="completion-display">0/4</div>
            </div>
        </div>
    </div>

    <div class="error-message" id="errorMessage"></div>

    <div class="game-container">
        <div class="maze-section">
            <h2 class="section-title">迷宫区域</h2>
            <div class="maze-grid" id="maze"></div>
        </div>

        <div class="controls-section">
            <h2 class="section-title">游戏控制</h2>

            <div class="player-controls">
                <div class="player-btn player-btn-1 active" data-player="1">
                    <div class="player-indicator"></div>
                    <div>玩家 1</div>
                </div>
                <div class="player-btn player-btn-2" data-player="2">
                    <div class="player-indicator"></div>
                    <div>玩家 2</div>
                </div>
                <div class="player-btn player-btn-3" data-player="3">
                    <div class="player-indicator"></div>
                    <div>玩家 3</div>
                </div>
                <div class="player-btn player-btn-4" data-player="4">
                    <div class="player-indicator"></div>
                    <div>玩家 4</div>
                </div>
            </div>

            <div class="difficulty-controls">
                <div class="difficulty-btn active" data-size="15">简单</div>
                <div class="difficulty-btn" data-size="25">中等</div>
                <div class="difficulty-btn" data-size="35">困难</div>
            </div>

            <button class="btn" id="generateBtn">生成新迷宫</button>
            <button class="btn secondary" id="solveBtn">显示解决方案</button>
            <button class="btn" id="resetBtn">重置玩家位置</button>

            <div class="stats">
                <div class="stat-label">当前时间</div>
                <div class="stat-value" id="timer">00:00</div>
            </div>

            <div class="stats">
                <div class="stat-label">最佳时间</div>
                <div class="stat-value" id="bestTime">00:00</div>
            </div>

            <div class="key-controls">
                <div class="key">W / ↑</div>
                <div class="key">A / ←</div>
                <div class="key">D / →</div>
                <div class="key">S / ↓</div>
                <div class="key">1-4</div>
                <div class="key">切换玩家</div>
                <div class="key">空格</div>
                <div class="key">生成</div>
                <div class="key">新迷宫</div>
            </div>
        </div>
    </div>

    <div class="instructions">
        <h3>游戏说明</h3>
        <ul>
            <li>使用<strong>方向键</strong>或<strong>WASD键</strong>移动<strong>当前玩家</strong></li>
            <li>按<strong>数字键1-4</strong>或点击上方玩家按钮切换当前玩家</li>
            <li>从<strong style="color:#4caf50">绿色起点</strong>出发，到达<strong
                    style="color:#f44336">红色终点</strong></li>
            <li>所有玩家都需要到达终点才能获胜</li>
            <li>按<strong>空格键</strong>或点击"生成新迷宫"按钮创建新的随机迷宫</li>
            <li>游戏会自动记录你的最佳完成时间</li>
            <li>选择不同难度级别改变迷宫大小</li>
        </ul>
    </div>
</div>

<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
    <div class="loading-text" id="loadingText">加载游戏中...</div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // 游戏配置
        const config = {
            mazeSize: 15,
            players: [
                {id: 1, x: 1, y: 1, color: '#ffeb3b', completed: false},
                {id: 2, x: 1, y: 1, color: '#2196F3', completed: false},
                {id: 3, x: 1, y: 1, color: '#4CAF50', completed: false},
                {id: 4, x: 1, y: 1, color: '#9C27B0', completed: false}
            ],
            currentPlayerId: 1,
            end: {x: 0, y: 0},
            timer: 0,
            timerInterval: null,
            bestTime: localStorage.getItem('mazeBestTime') || 0,
            isSolving: false,
            gameId: null
        };

        // DOM元素
        const mazeElement = document.getElementById('maze');
        const generateBtn = document.getElementById('generateBtn');
        const solveBtn = document.getElementById('solveBtn');
        const resetBtn = document.getElementById('resetBtn');
        const timerElement = document.getElementById('timer');
        const bestTimeElement = document.getElementById('bestTime');
        const difficultyBtns = document.querySelectorAll('.difficulty-btn');
        const playerBtns = document.querySelectorAll('.player-btn');
        const currentPlayerDisplay = document.getElementById('current-player-display');
        const gameIdDisplay = document.getElementById('game-id-display');
        const difficultyDisplay = document.getElementById('difficulty-display');
        const completionDisplay = document.getElementById('completion-display');
        const loadingOverlay = document.getElementById('loadingOverlay');
        const loadingText = document.getElementById('loadingText');
        const errorMessage = document.getElementById('errorMessage');

        // 显示加载状态
        function showLoading(message) {
            loadingText.textContent = message;
            loadingOverlay.style.display = 'flex';
        }

        // 隐藏加载状态
        function hideLoading() {
            loadingOverlay.style.display = 'none';
        }

        // 显示错误消息
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 5000);
        }

        // 初始化游戏
        async function initGame() {
            showLoading("初始化游戏...");

            // 尝试从URL获取游戏ID
            const urlParams = new URLSearchParams(window.location.search);
            const gameId = urlParams.get('game_id');

            try {
                if (gameId) {
                    // 加载指定游戏
                    await loadGame(gameId);
                } else {
                    // 加载最新游戏
                    await loadLatestGame();
                }
            } catch (error) {
                showError(`游戏初始化失败: ${error.message}`);
            } finally {
                hideLoading();
            }

            // 设置事件监听
            document.addEventListener('keydown', handleKeyPress);
            generateBtn.addEventListener('click', generateMaze);
            solveBtn.addEventListener('click', toggleSolveMaze);
            resetBtn.addEventListener('click', resetPlayers);

            difficultyBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    difficultyBtns.forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    config.mazeSize = parseInt(btn.dataset.size);
                });
            });

            playerBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    const playerId = parseInt(btn.dataset.player);
                    switchPlayer(playerId);
                    savePlayerPosition();
                });
            });
        }

        // 从后端加载指定游戏
        async function loadGame(gameId) {
            showLoading(`加载游戏 ${gameId}...`);

            try {
                const response = await fetch(`/get_game_data?game_id=${gameId}`);

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                const gameData = await response.json();

                if (gameData.status === 'success') {
                    // 更新游戏配置
                    config.maze = gameData.maze_data;
                    config.mazeSize = gameData.maze_size;
                    config.gameId = gameData.game_id;
                    config.end = {x: gameData.maze_size-2, y: gameData.maze_size-2};

                    // 更新玩家位置
                    gameData.players.forEach(playerData => {
                        const player = config.players.find(p => p.id === playerData.player_number);
                        if (player) {
                            player.x = playerData.x_position;
                            player.y = playerData.y_position;
                            player.completed = playerData.is_completed;
                        }
                    });

                    // 更新游戏状态
                    if (gameData.game_state) {
                        config.currentPlayerId = gameData.game_state.current_player;
                    }

                    // 更新游戏信息显示
                    gameIdDisplay.textContent = gameData.game_id;
                    difficultyDisplay.textContent = gameData.difficulty;

                    // 更新完成度
                    updateCompletionDisplay();

                    // 渲染迷宫
                    renderMaze();

                    // 更新当前玩家显示
                    currentPlayerDisplay.textContent = config.currentPlayerId;
                    updatePlayerButtons();

                    console.log(`游戏 ${gameId} 加载成功`);
                } else {
                    throw new Error(gameData.message || '加载游戏失败');
                }
            } catch (error) {
                console.error('加载游戏失败:', error);
                showError(`加载游戏失败: ${error.message}`);
                await createNewGame();
            } finally {
                hideLoading();
            }
        }

        // 更新玩家按钮状态
        function updatePlayerButtons() {
            playerBtns.forEach(btn => {
                const playerId = parseInt(btn.dataset.player);
                const player = config.players.find(p => p.id === playerId);

                // 移除所有状态类
                btn.classList.remove('active', 'completed');

                // 设置当前玩家
                if (playerId === config.currentPlayerId) {
                    btn.classList.add('active');
                }

                // 设置已完成玩家
                if (player && player.completed) {
                    btn.classList.add('completed');
                }
            });
        }

        // 加载最新游戏
        async function loadLatestGame() {
            showLoading("加载最新游戏...");

            try {
                const response = await fetch('/get_latest_game');

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                const gameData = await response.json();

                if (gameData.status === 'success' && gameData.game_id) {
                    await loadGame(gameData.game_id);
                } else {
                    throw new Error('没有找到最新游戏');
                }
            } catch (error) {
                console.error('加载最新游戏失败:', error);
                showError(`加载最新游戏失败: ${error.message}`);
                await createNewGame();
            }
        }

        // 创建新游戏
        async function createNewGame() {
            showLoading("创建新游戏...");

            try {
                // 获取当前选择的难度
                const activeDifficulty = document.querySelector('.difficulty-btn.active');
                const mazeSize = activeDifficulty ? parseInt(activeDifficulty.dataset.size) : 15;

                // 发送请求创建新游戏
                const response = await fetch('/create_new_game', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    },
                    body: JSON.stringify({ size: mazeSize })
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                const result = await response.json();

                if (result.status === 'success') {
                    // 加载新创建的游戏
                    await loadGame(result.game_id);
                } else {
                    throw new Error(result.message || '创建新游戏失败');
                }
            } catch (error) {
                console.error('创建新游戏失败:', error);
                showError(`创建新游戏失败: ${error.message}`);
            } finally {
                hideLoading();
            }
        }

        // 保存玩家位置
        async function savePlayerPosition() {
            if (!config.gameId) return;

            try {
                const player = config.players.find(p => p.id === config.currentPlayerId);
                if (!player) return;

                const response = await fetch('/update_player_position', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    },
                    body: JSON.stringify({
                        game_id: config.gameId,
                        player_id: player.id,
                        x: player.x,
                        y: player.y,
                        completed: player.completed
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                const result = await response.json();
                if (result.status !== 'success') {
                    console.error('保存玩家位置失败:', result.message);
                }
            } catch (error) {
                console.error('保存玩家位置失败:', error);
                showError(`保存玩家位置失败: ${error.message}`);
            }
        }

        // 切换当前玩家
        function switchPlayer(playerId) {
            config.currentPlayerId = playerId;
            currentPlayerDisplay.textContent = playerId;
            updatePlayerButtons();
            renderMaze();
        }

        // 渲染迷宫到DOM
        function renderMaze() {
            if (!config.maze) return;

            mazeElement.innerHTML = '';
            mazeElement.style.gridTemplateColumns = `repeat(${config.mazeSize}, 1fr)`;

            for (let y = 0; y < config.mazeSize; y++) {
                for (let x = 0; x < config.mazeSize; x++) {
                    const cell = document.createElement('div');
                    cell.classList.add('cell');

                    // 添加对应的类
                    if (config.maze[y][x] === 1) {
                        cell.classList.add('wall');
                    } else {
                        cell.classList.add('path');
                    }

                    if (x === 1 && y === 1) {
                        cell.classList.add('start');
                    }

                    if (x === config.end.x && y === config.end.y) {
                        cell.classList.add('end');
                    }

                    // 检查此单元格是否有玩家
                    const playersHere = config.players.filter(p => p.x === x && p.y === y);

                    // 如果有玩家，添加玩家标记
                    playersHere.forEach(player => {
                        const playerMarker = document.createElement('div');
                        playerMarker.classList.add('player-marker', `player-${player.id}`);
                        playerMarker.textContent = player.id;
                        playerMarker.style.backgroundColor = player.color;

                        if (player.id === config.currentPlayerId) {
                            playerMarker.classList.add('active');
                        }

                        cell.appendChild(playerMarker);
                        cell.classList.add('player');

                        // 如果玩家已完成，添加特殊样式
                        if (player.completed) {
                            playerMarker.style.boxShadow = '0 0 8px #4CAF50';
                        }
                    });

                    mazeElement.appendChild(cell);
                }
            }
        }

        // 处理键盘事件
        function handleKeyPress(e) {
            // 空格键生成新迷宫
            if (e.key === ' ' || e.key === 'Spacebar') {
                generateMaze();
                return;
            }

            // R键重置玩家位置
            if (e.key === 'r' || e.key === 'R') {
                resetPlayers();
                return;
            }

            // 数字键1-4切换玩家
            if (e.key >= '1' && e.key <= '4') {
                const playerId = parseInt(e.key);
                switchPlayer(playerId);
                savePlayerPosition();
                return;
            }

            let dx = 0, dy = 0;

            // 方向键和WASD控制
            if (e.key === 'ArrowUp' || e.key === 'w' || e.key === 'W') dy = -1;
            if (e.key === 'ArrowRight' || e.key === 'd' || e.key === 'D') dx = 1;
            if (e.key === 'ArrowDown' || e.key === 's' || e.key === 'S') dy = 1;
            if (e.key === 'ArrowLeft' || e.key === 'a' || e.key === 'A') dx = -1;

            // 如果有移动方向
            if (dx !== 0 || dy !== 0) {
                movePlayer(dx, dy);
            }
        }

        // 移动玩家
        function movePlayer(dx, dy) {
            const player = config.players.find(p => p.id === config.currentPlayerId);
            if (!player || player.completed) return;

            const newX = player.x + dx;
            const newY = player.y + dy;

            // 检查是否可以移动（在边界内且不是墙）
            if (newX >= 0 && newX < config.mazeSize &&
                newY >= 0 && newY < config.mazeSize &&
                config.maze[newY][newX] !== 1) {

                // 启动计时器（如果尚未启动）
                if (!config.timerInterval) {
                    startTimer();
                }

                // 更新玩家位置
                player.x = newX;
                player.y = newY;

                // 重新渲染迷宫
                renderMaze();

                // 保存玩家位置
                savePlayerPosition();

                // 检查是否到达终点
                if (newX === config.end.x && newY === config.end.y) {
                    player.completed = true;

                    // 更新完成度显示
                    updateCompletionDisplay();
                    updatePlayerButtons();

                    // 检查是否所有玩家都已完成
                    if (config.players.every(p => p.completed)) {
                        finishGame();
                    } else {
                        // 自动切换到下一个未完成的玩家
                        const nextPlayer = config.players.find(p => !p.completed);
                        if (nextPlayer) {
                            switchPlayer(nextPlayer.id);
                        }
                    }

                    // 更新玩家完成状态
                    savePlayerPosition();
                }
            }
        }

        // 生成新迷宫
        async function generateMaze() {
            // 重置游戏状态
            clearInterval(config.timerInterval);
            config.timer = 0;
            updateTimerDisplay();

            // 重置玩家状态
            config.players.forEach(player => {
                player.completed = false;
            });

            // 更新完成度显示
            updateCompletionDisplay();
            updatePlayerButtons();

            // 创建新游戏
            await createNewGame();
        }

        // 更新完成度显示
        function updateCompletionDisplay() {
            const completedCount = config.players.filter(p => p.completed).length;
            completionDisplay.textContent = `${completedCount}/4`;
        }

        // 重置玩家位置
        async function resetPlayers() {
            // 重置玩家状态
            config.players.forEach(player => {
                player.x = 1;
                player.y = 1;
                player.completed = false;
            });

            // 更新完成度显示
            updateCompletionDisplay();
            updatePlayerButtons();

            // 重新渲染迷宫
            renderMaze();

            // 重置计时器
            clearInterval(config.timerInterval);
            config.timer = 0;
            updateTimerDisplay();
            config.timerInterval = null;

            // 保存重置后的位置
            for (const player of config.players) {
                await savePlayerPosition();
            }
        }

        // 获取CSRF token的函数
        function getCSRFToken() {
            const cookieValue = document.cookie
                .split('; ')
                .find(row => row.startsWith('csrftoken='))
                ?.split('=')[1];
            return cookieValue;
        }

        // 开始计时
        function startTimer() {
            config.timerInterval = setInterval(() => {
                config.timer++;
                updateTimerDisplay();
            }, 1000);
        }

        // 更新计时器显示
        function updateTimerDisplay() {
            const minutes = Math.floor(config.timer / 60).toString().padStart(2, '0');
            const seconds = (config.timer % 60).toString().padStart(2, '0');
            timerElement.textContent = `${minutes}:${seconds}`;
        }

        // 更新最佳时间显示
        function updateBestTimeDisplay() {
            if (config.bestTime > 0) {
                const minutes = Math.floor(config.bestTime / 60).toString().padStart(2, '0');
                const seconds = (config.bestTime % 60).toString().padStart(2, '0');
                bestTimeElement.textContent = `${minutes}:${seconds}`;
            } else {
                bestTimeElement.textContent = "00:00";
            }
        }

        // 完成游戏
        function finishGame() {
            clearInterval(config.timerInterval);

            // 更新最佳时间
            if (config.bestTime === 0 || config.timer < config.bestTime) {
                config.bestTime = config.timer;
                localStorage.setItem('mazeBestTime', config.bestTime);
                updateBestTimeDisplay();

                // 显示庆祝消息
                alert(`恭喜！所有玩家以${timerElement.textContent}的成绩完成了迷宫！新记录！`);
            } else {
                alert(`恭喜！所有玩家以${timerElement.textContent}的成绩完成了迷宫！`);
            }
        }

        // 切换显示解决方案
        function toggleSolveMaze() {
            config.isSolving = !config.isSolving;
            solveBtn.textContent = config.isSolving ? '隐藏解决方案' : '显示解决方案';

            if (config.isSolving) {
                solveMaze();
            } else {
                renderMaze();
            }
        }

        // 解决迷宫（使用广度优先搜索）
        function solveMaze() {
            const size = config.mazeSize;
            const queue = [{x: 1, y: 1, path: []}];
            const visited = new Set();
            visited.add('1,1');

            while (queue.length > 0) {
                const {x, y, path} = queue.shift();

                // 到达终点
                if (x === config.end.x && y === config.end.y) {
                    // 高亮显示路径
                    for (const [px, py] of path) {
                        const index = py * size + px;
                        mazeElement.children[index].classList.add('visited');
                    }
                    return;
                }

                // 探索四个方向
                const directions = [[0, -1], [1, 0], [0, 1], [-1, 0]];
                for (const [dx, dy] of directions) {
                    const nx = x + dx;
                    const ny = y + dy;
                    const key = `${nx},${ny}`;

                    // 检查是否可移动且未访问过
                    if (nx >= 0 && nx < size && ny >= 0 && ny < size &&
                        config.maze[ny][nx] !== 1 && !visited.has(key)) {

                        visited.add(key);
                        queue.push({
                            x: nx,
                            y: ny,
                            path: [...path, [x, y]]
                        });
                    }
                }
            }
        }

        // 初始化游戏
        initGame();
    });
</script>
</body>
</html>